﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;

namespace RBAC.APP
{
    public class Role
    {
        #region Fields
        /// <summary>
        /// 角色Id
        /// </summary>
        private string roleId;
        /// <summary>
        /// 角色Id
        /// </summary>
        public string RoleId
        {
            get { return roleId; }
            //set { roleId = value; }
        }
        /// <summary>
        /// 角色名称
        /// </summary>
        private string roleName;
        /// <summary>
        /// 角色名称
        /// </summary>
        public string RoleName
        {
            get { return roleName; }
            set { roleName = value; }
        }
        /// <summary>
        /// 角色描述
        /// </summary>
        private string roleDescription;
        /// <summary>
        /// 角色描述
        /// </summary>
        public string RoleDescription
        {
            get { return roleDescription; }
            set { roleDescription = value; }
        }
        #endregion Fields

        #region StaticFunctions

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <param name="roleName">角色名称</param>
        /// <param name="roleDescription">角色描述</param>
        public static int AddRole(string roleId, string roleName, string roleDescription)
        {
            //*****10300*****
            //在表：SRole中增加一条记录
            //（1）参数：roleId。新角色Id，不能为空，必须为英文，自动全转换成小写
            //若新roleId已存在，报错103002。新roleId为空，报错103003。
            //（2）参数：roleName。新角色名，不能为空。
            //roleName为空，报错103004
            //（3）参数：roleDescription。角色描述，可以为空。
            //（4）返回：int
            //添加成功，返回103001；添加失败，返回103009
            //--------------------------------------------------------
            //本方法需要Log的情况：103001，103009，content为“代号,roleId”
            string lowerroleID = string.Empty;
            if (string.IsNullOrEmpty(roleId))
                return 103003;
            else
            {
                if (!CheckString(roleId, @"^[A-Za-z]+$"))
                    return 103003;
                else
                {
                    lowerroleID = roleId.ToLower();
                    if (string.IsNullOrEmpty(roleName))
                        return 103004;
                    else
                    {
                        RBAC.ORM.DAL.SRole optSRole = new ORM.DAL.SRole();
                        RBAC.ORM.Model.SRole mySRole = new ORM.Model.SRole();
                        bool ok = optSRole.Exists(lowerroleID);
                        if (ok)
                            return 103002;
                        else
                        {
                            mySRole.roleID = lowerroleID;
                            mySRole.rolename = roleName;
                            mySRole.roledescription = roleDescription;
                            bool Ifok = optSRole.Add(mySRole);
                            if (Ifok)
                            {
                                Operator.MakeLog(ObjectType.ROLE, "103001" + lowerroleID);
                                return 103001;
                            }
                            else
                            {
                                Operator.MakeLog(ObjectType.ROLE, "103009" + lowerroleID);
                                return 103009;
                            }
                        }
                    }
                }
            }

        }
        /// <summary>
        /// 匹配字符串
        /// </summary>
        /// <param name="uncheckedString">待匹配字符串</param>
        /// <param name="pattern">正则表达式</param>
        /// <returns></returns>
        private static bool CheckString(string uncheckedString, string pattern)
        {
            Regex regex = new Regex(pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline | RegexOptions.IgnoreCase);
            Match match = regex.Match(uncheckedString);
            if (match.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId">角色Id</param>
        public static int DeleteRole(string roleId)
        {
            //*****10301*****
            //删除表：SRole中的一条记录
            //（1）参数：roleID。不能为空。
            //若roleID不存在，返回103014。
            //（2）执行删除先决条件：
            //（2.1）删除表：SURD中所有roleID为此的记录。在此过程中发生的任何错误，报错103012。
            //（2.2）删除表：SRoleFunction中所有roleID为此的记录。在此过程中发生的任何错误，报错103013。
            //（3）返回：int
            //删除成功，返回103011；删除发生错误，返回103019。
            //--------------------------------------------------------
            //本方法需要Log的情况：103011，103019，103012，103013，content为“代号,roleId”
            RBAC.ORM.DAL.SRole optSRole=new ORM.DAL.SRole();
            RBAC.ORM.DAL.SURD optSURD = new ORM.DAL.SURD();
            RBAC.ORM.DAL.SRoleFunction optSRoleFunction = new ORM.DAL.SRoleFunction();
            if (string.IsNullOrEmpty(roleId))
                return 103014;
            else
            {
                bool ok = optSRole.Exists(roleId);
                if (!ok)
                    return 103014;
                else
                {
                    DataSet ds = optSURD.GetList("roleID='" + roleId + "'");
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        bool Ifok = optSURD.Delete(decimal.Parse(ds.Tables[0].Rows[i]["id"].ToString()));
                        if (!Ifok)
                        {
                            Operator.MakeLog(ObjectType.ROLE, "103012" + roleId);
                            return 103012;
                        }
                    }
                    DataSet ds1 = optSRoleFunction.GetList("roleID='" + roleId + "'");
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        bool Ifok = optSRoleFunction.Delete(int.Parse(ds.Tables[0].Rows[i]["id"].ToString()));
                        if (!Ifok)
                        {
                            Operator.MakeLog(ObjectType.ROLE, "103013" + roleId);
                            return 103013;
                        }
                    }
                    bool ok1 = optSRole.Delete(roleId);
                    if (ok1)
                    {
                        Operator.MakeLog(ObjectType.ROLE, "103011" + roleId);
                        return 103011;
                    }
                    else
                    {
                        Operator.MakeLog(ObjectType.ROLE, "103019" + roleId);
                        return 103019;
                    }
                }
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleObject">角色对象</param>
        public static int DeleteRole(Role roleObject)
        {
            //--------------------------------------------------------
            //此方法参照DeleteRole(string roleId)
            //--------------------------------------------------------
            return Role.DeleteRole(roleObject.roleId.ToString());
        }

        /// <summary>
        /// 阅读角色
        /// </summary>
        /// <param name="roleId">角色Id</param>
        public static Role ReadRole(string roleId)
        {
            //--------------------------------------------------------
            //获取表：SRole中的一条记录
            //参数（1）：roleId，不可为空
            //若为空，返回null
            //若不存在该role，返回null
            //返回（2）：Role对象
            //--------------------------------------------------------
            RBAC.ORM.DAL.SRole optSRole = new ORM.DAL.SRole();
            RBAC.ORM.Model.SRole mySRole = new ORM.Model.SRole();
            if (string.IsNullOrEmpty(roleId))
                return null;
            else
            {
                bool ok = optSRole.Exists(roleId);
                if (!ok)
                    return null;
                else
                {
                    mySRole=optSRole.GetModel(roleId);
                    Role myRole = new Role();
                    myRole.roleId = mySRole.roleID;
                    myRole.roleName = mySRole.rolename;
                    myRole.roleDescription = mySRole.roledescription;
                    return myRole;
                }
            }
        }

        /// <summary>
        /// 阅读角色
        /// </summary>
        /// <param name="howMany">数量</param>
        public static List<Role> ReadRoles(int? howMany)
        {
            //--------------------------------------------------------
            //参考SearchRoles方法
            //--------------------------------------------------------
            return SearchRoles(null, howMany);
        }

        /// <summary>
        /// 搜索角色
        /// </summary>
        /// <param name="roleNameorDescription">角色名或角色描述</param>
        /// <param name="howMany">数量</param>
        public static List<Role> SearchRoles(string roleNameorDescription, int? howMany)
        {
            //--------------------------------------------------------
            //搜索表:SRole中一定数量的记录，数量为参数howMany。
            //（1）参数：howMany，可为空
            //若为空，则参数值为RBACAPPDefaultValue.howMany_RolesToRead值
            //如果读取上述参数howMany_RolesToRead异常，howMany默认为100
            //（2）参数：roleNameorDescription，可为空
            //若为空，则搜索所有内容，若不为空，则搜索表：SRole中roleName或roledescription字段值中包含此内容的记录
            //（3）返回：泛型Role
            //将获得的记录组织成泛型返回，根据roleId正排序。在构建单个Role对象时使用ReadRole方法
            //若不存在，返回null。
            //--------------------------------------------------------
            if (howMany == null)
            {
                try
                {
                    howMany = RBACAPPDefaultValue.HowMany_RolesToRead;
                }
                catch
                {
                    howMany = 100;
                }
            }
            RBAC.ORM.DAL.SRole optSRole = new ORM.DAL.SRole();
            List<Role> myListRole = new List<Role>();
            if (string.IsNullOrEmpty(roleNameorDescription))
            {
                DataSet ds = optSRole.GetList("1=1 order by roleID asc");
                if (ds.Tables[0].Rows.Count == 0)
                    return null;
                else
                {
                    if (howMany < ds.Tables[0].Rows.Count)
                    {
                        for (int i = 0; i < howMany; i++)
                            myListRole.Add(ReadRole(ds.Tables[0].Rows[i]["roleID"].ToString()));
                    }
                    else
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            myListRole.Add(ReadRole(ds.Tables[0].Rows[i]["roleID"].ToString()));
                        }
                    }
                    return myListRole;
                }
            }
            else
            {
                DataSet ds = optSRole.GetList("rolename like '%" + roleNameorDescription + "%' or roledescription like '%" + roleNameorDescription + "%' order by roleID asc");
                if (ds.Tables[0].Rows.Count == 0)
                    return null;
                else
                {
                    if (howMany < ds.Tables[0].Rows.Count)
                    {
                        for (int i = 0; i < howMany; i++)
                            myListRole.Add(ReadRole(ds.Tables[0].Rows[i]["roleID"].ToString()));
                    }
                    else
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            myListRole.Add(ReadRole(ds.Tables[0].Rows[i]["roleID"].ToString()));
                        }
                    }
                    return myListRole;
                }
            }

        }
        #endregion StaticFunctions

        #region NonStaticFunctions
        /// <summary>
        /// 更新角色信息
        /// </summary>
        public int Update()
        {
            //*****10302*****
            //更新表：SRole中的记录
            //（1）参数roleId，为当前的roleId。若roleId为null或空，则报错103023.
            //（2）参数roleName，为当前的roleName，不可为空。若roleName为空，报错103022.
            //（3）参数roleDescription，为当前的roleDescription。
            //（4）返回：int
            //若修改成功，返回103021；若修改失败，返回103029
            //--------------------------------------------------------
            //本方法需要Log的情况：103021，103029。content为“代号,roleId”
            if (string.IsNullOrEmpty(this.roleId))
                return 103023;
            else if (string.IsNullOrEmpty(this.roleName))
                return 103022;
            else
            {
                RBAC.ORM.Model.SRole mySRole = new ORM.Model.SRole();
                RBAC.ORM.DAL.SRole optSRole = new ORM.DAL.SRole();
                mySRole.roleID =this.roleId;
                mySRole.rolename = this.roleName;
                mySRole.roledescription = this.roleDescription;
                bool ok=optSRole.Update(mySRole);
                if (ok)
                {
                    Operator.MakeLog(ObjectType.ROLE,"103021"+roleId);
                    return 103021;
                }
                else
                {
                    Operator.MakeLog(ObjectType.ROLE,"103029"+roleId);
                    return 103029;
                }
            }
        }

        /// <summary>
        /// 引用用户
        /// </summary>
        public List<User> ReferenceUser
        {
            get
            {
                //--------------------------------------------------------
                //从表：SURD中找出roleID为此的userId。
                //若不存在，返回null。
                //若存在，返回User的泛型，以userID正排序，可调用User.ReadUser方法获取单个User对象
                //注意：消除结果中重复的User
                //--------------------------------------------------------
                RBAC.ORM.DAL.SURD optSURD=new ORM.DAL.SURD();
                DataSet ds = optSURD.GetList("roleID='" + this.roleId + "' order by userID asc");
                if (ds.Tables[0].Rows.Count == 0)
                    return null;
                else
                {
                    List<User> myListUser = new List<User>();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (myListUser.Contains(RBAC.APP.User.ReadUser(ds.Tables[0].Rows[i]["userID"].ToString())))
                            continue;
                        myListUser.Add(RBAC.APP.User.ReadUser(ds.Tables[0].Rows[i]["userID"].ToString()));
                    }
                    return myListUser;
                }
            }
        }

        /// <summary>
        /// 包含方法
        /// </summary>
        public List<Function> Function
        {
            get
            {
                //--------------------------------------------------------
                //从表：SRoleFunction中找出roleID为此的funID
                //若不存在，返回null。
                //若存在，返回Function的泛型，以funID正排序，可调用Function.ReadFunction方法获取单个Function对象
                //--------------------------------------------------------
                RBAC.ORM.DAL.SRoleFunction optSRoleFunction = new ORM.DAL.SRoleFunction();
                DataSet ds = optSRoleFunction.GetList("roleID='" + this.roleId + "' order by funID asc");
                if (ds.Tables[0].Rows.Count == 0)
                    return null;
                else
                {
                    List<Function> myListFunction = new List<Function>();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        myListFunction.Add(RBAC.APP.Function.ReadFunction(ds.Tables[0].Rows[i]["funID"].ToString()));
                    }
                    return myListFunction;
                }
            }
        }
        #endregion NonStaticFunctions
    }
}
